define(['moment'], function (moment) {
    return ['$scope', '$filter', '$stateParams', 'config', 'MMWService', '$mdDialog',
    function ($scope, $filter, $stateParams, config, $MMWService, $mdDialog) {
        $scope.init = function(){
            $scope.mode = {0:''};
            $scope.auto_next = '1';
            $scope.handle_type = '2';
            $scope.itemList = [];
            $scope.subItemList = [];
            $scope.handleReasonList = [];
            $scope.condition = {
                reason_no:'',
                op_no:'',
                line_no:''
            };
            $scope.handleData = { old_seq_no:'', new_seq_no:'', seq_list:[]};
            $scope.isSelectAll = false;
        };

        $scope.back = function(){
            $scope.$root.hideMenu();
            $scope.$root.changeProgram('home', true);
        };

        $scope.getHandleType = function(){
            if($scope.handle_type == '2'){
                return ['handle-fix'];
            } else if($scope.handle_type == '1'){
                return ['handle-replace'];
            } else if($scope.handle_type == '3'){
                return ['handle-scrapped'];
            } else if($scope.handle_type == '4'){
                return ['handle-single-fix'];
            }
        }
        $scope.setHandleType = function(handle_type){
            if($scope.handle_type != handle_type){
                $scope.handle_type = handle_type;
                $scope.handleData = {old_seq_no:'', new_seq_no:'', seq_list:[]};
                $scope.handleReasonList = [];
            }
            if(handle_type == '4'){
                // 切換到單次維修狀態需刷新成未勾選情況，避免從其他狀態勾選後，切換到單次維修狀態所造成多選的情況
                $scope.itemList.forEach(function(item){
                    item.slected = false;
                });
            }
        }
        // 開啟相機掃QRCode
        $scope.qrcode = function(target){
            $scope.$root.OpenScanner({
                after : function(result){
                    target = result.text;
                },
                exception: function(){
                    //目前裝置無法使用相機
                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                },
                orientation : 'landscape'
            });
        }

        // 開啟相機掃QRCode
        $scope.qrcode_pcs = function () {
            $scope.$root.OpenScanner({
                after: function (result) {
                    $scope.condition.pcs_no = result.text;
                },
                exception: function () {
                    //目前裝置無法使用相機
                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                },
                orientation: 'landscape'
            });
        }
        // 開啟相機掃QRCode
        $scope.qrcode_unit = function () {
            $scope.$root.OpenScanner({
                after: function (result) {
                    $scope.condition.unit_no = result.text;
                },
                exception: function () {
                    //目前裝置無法使用相機
                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                },
                orientation: 'landscape'
            });
        }

        function update_bdreason(master_sid,reason_info){
            let content = {
                master_sid: master_sid,
                reason_list:reason_info
            }
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SN.pcs_badreason_save_process',
                content,
                success: function (data) {
                   
                }
            });
        }
        //修改不良原因
        $scope.loadBdreason = function(item){
            $mdDialog.serviceDialog('E01badreasonService',{
                op_no: item.op_no,
                itemList:item.badreason_detail||[],
                callback:function(dialog){
                    //20200602 modify by dustdusk for M#71031: 修正刪除後顯示內容沒有同步刪除
                    if(dialog.itemList.length > 0){
                        item.reason_desc = '';
                        item.badreason_detail = dialog.itemList;
                        let send_no;
                        for(var i=0;i<item.badreason_detail.length;i++){
                            if(i==0){
                                item.reason_desc = item.badreason_detail[i].reason_name;
                                send_no = item.badreason_detail[i].reason_no;
                            } else {
                                item.reason_desc += ', ' + item.badreason_detail[i].reason_name;
                                send_no += ', ' + item.badreason_detail[i].reason_no;
                            }
                        }
                        update_bdreason(item.master_sid,send_no);
                        dialog.hide();
                    }else{
                        $scope.$root.showAlert($filter('translate')('E07.msg.reason_empty'));
                    }
                },
                close:function(){
                }
            });
        }

        // 成品序號不良原因編號開窗
        $scope.loadReason = function(){
            $MMWService.showQueryListPNIG({
                page_mode: 'pcs_badreason_get',
                condition: [
                    {name:$filter('translate')('common.queryList.badReason_c'), column_name:'a.ReasonNo', query_mode:'2', value:$scope.condition.reason_no}
                ],
                header: [
                    {label:$filter('translate')('common.queryList.badReason_c'), code:'reason_no'},
                    {label:$filter('translate')('common.queryList.badReason_n'), code:'reason_name'}
                ],
                setCondition:function(conditions){
                    if($scope.condition.line_no != '')
                        conditions.push({column_name:'PDLineNo', query_mode:'0', value:$scope.condition.line_no, merge_condition_model:'AND' });
                    if($scope.condition.op_no != '')
                        conditions.push({column_name:'OPNo', query_mode:'0', value:$scope.condition.op_no, merge_condition_model:'AND' });
                    return conditions;
                },
                selectCode: $scope.condition.reason_no,
                confirm : function(selectItem){
                    $scope.condition.reason_no = selectItem.reason_no;
                }
            });
        }
        
        // 成品序號不良原因編號開窗
        $scope.loadReason = function(){
            $MMWService.showQueryListPNIG({
                page_mode: 'pcs_badreason_get',
                condition: [
                    {name:$filter('translate')('common.queryList.badReason_c'), column_name:'a.ReasonNo', query_mode:'2', value:$scope.condition.reason_no}
                ],
                header: [
                    {label:$filter('translate')('common.queryList.badReason_c'), code:'reason_no'},
                    {label:$filter('translate')('common.queryList.badReason_n'), code:'reason_name'}
                ],
                setCondition:function(conditions){
                    if($scope.condition.line_no != '')
                        conditions.push({column_name:'PDLineNo', query_mode:'0', value:$scope.condition.line_no, merge_condition_model:'AND' });
                    if($scope.condition.op_no != '')
                        conditions.push({column_name:'OPNo', query_mode:'0', value:$scope.condition.op_no, merge_condition_model:'AND' });
                    return conditions;
                },
                selectCode: $scope.condition.reason_no,
                confirm : function(selectItem){
                    $scope.condition.reason_no = selectItem.reason_no;
                }
            });
        }

        // 生產線開窗
        $scope.loadLine = function(){
            $MMWService.showQueryListPNIG({
                page_mode: 'pcs_badreason_line_get',
                condition: [
                    {name:$filter('translate')('common.queryList.line_c'), column_name:'a.PDLineNo', query_mode:'2', value:$scope.condition.line_no}
                ],
                header: [
                    {label:$filter('translate')('common.queryList.line_c'), code:'pdline_no'},
                    {label:$filter('translate')('common.queryList.line_n'), code:'pdline_name'}
                ],
                setCondition:function(conditions){
                    if($scope.condition.reason_no != '')
                        conditions.push({column_name:'ReasonNo', query_mode:'0', value:$scope.condition.reason_no, merge_condition_model:'AND' });
                    if($scope.condition.op_no != '')
                        conditions.push({column_name:'OPNo', query_mode:'0', value:$scope.condition.op_no, merge_condition_model:'AND' });
                    return conditions;
                },
                selectCode: $scope.condition.line_no,
                confirm : function(selectItem){
                    $scope.condition.line_no = selectItem.pdline_no;
                }
            });
        }
        // 作業站開窗
        $scope.loadOP = function(){
            $MMWService.showQueryListPNIG({
                page_mode: 'pcs_badreason_op_get',
                condition: [
                    {name:$filter('translate')('common.queryList.op_c'), column_name:'a.OPNo', query_mode:'2', value:$scope.condition.op_no}
                ],
                header: [
                    {label:$filter('translate')('common.queryList.op_c'), code:'op_no'},
                    {label:$filter('translate')('common.queryList.op_n'), code:'op_name'}
                ],
                setCondition:function(conditions){
                    if($scope.condition.line_no != '')
                        conditions.push({column_name:'PDLineNo', query_mode:'0', value:$scope.condition.line_no, merge_condition_model:'AND' });

                    if($scope.condition.reason_no != '')
                        conditions.push({column_name:'ReasonNo', query_mode:'0', value:$scope.condition.reason_no, merge_condition_model:'AND' });

                    return conditions;
                },
                selectCode: $scope.condition.op_no,
                confirm : function(selectItem){
                    $scope.condition.op_no = selectItem.op_no;
                }
            });
        }
        // 報廢原因編號開窗
        $scope.loadHandleReason = function(item){
            $MMWService.showQueryListPNIG({
                page_mode: 15,
                condition: [
                    {name:$filter('translate')('common.queryList.badReason_c'), column_name:'A.ErrorNo', query_mode:'2', value:''}
                ],
                header: [
                    {label:$filter('translate')('common.queryList.badReason_c'), code:'page_no'},
                    {label:$filter('translate')('common.queryList.badReason_n'), code:'page_name'}
                ],
                setCondition:function(conditions){
                    conditions.push({column_name:'OPNo', query_mode:'0', value:item.op_no, merge_condition_model:'AND' });
                    return conditions;
                },
                selectCode: item.scrapped_reason_no,
                confirm : function(selectItem){
                    item.scrapped_reason_no = selectItem.page_no;
                    item.scrapped_reason_name = selectItem.page_name;
                    item.slected = true;
                },
                cancel : function(dialog){
                    dialog.hide();
                    item.scrapped_reason_no = undefined;
                    item.scrapped_reason_name = undefined;
                    item.slected = false;
                }
            });
        }
        // 查詢
        $scope.search = function(){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SN.pcs_badreason_info_get',
                content: $scope.condition,
                success: function (data) {
                    $scope.now_item = undefined;
                    $scope.itemList = data;
                    $scope.subItemList = [];
                    $scope.handleData = { old_seq_no:'', new_seq_no:'', seq_list:[]};
                    $scope.handleReasonList = [];
                    if($scope.itemList && $scope.itemList.length > 0){
                        $scope.selectItem($scope.itemList[0]);
                    }
                }
            });
        };

        // 成品序號勾選
        $scope.checkItem = function(item){
            if($scope.handle_type == '4'){
                if(item.slected){
                    item.slected = false;
                } else {
                    var filter_list = $filter('filter')($scope.itemList, { slected: true });
                    if(filter_list && filter_list.length > 0){
                        // 單筆維修只可勾選一筆資料
                        $scope.$root.showAlert($filter('translate')('E07.msg.column3'));
                    } else {
                        item.slected = true;
                    }
                }    
            } else {
                item.slected = !item.slected;
            }
        }

        //成品序號選擇
        $scope.selectItem = function(item){
            if($scope.now_item == undefined || item.master_sid != $scope.now_item.master_sid){
                $scope.now_item = item;
                pcs_unit_info_get(item, function(data){
                    $scope.subItemList = data;
                });
                // 取得解綁工序
                position_unbind_info_get(item, function(data){
                    if(data.detail_list && data.detail_list.length > 0){
                        $scope.now_item.detail_list = data.detail_list;
                        // 系統參數 - 工位機送修強制解綁當站(PCSMaterialRepaireClear) 啟用時，第一筆工序一律勾選
                        if(config.cache.sys_parameter.PCSMaterialRepaireClear == 1){
                            $scope.now_item.detail_list[0].isSelect = true; // 是否勾選
                            $scope.now_item.detail_list[0].isModify = false; // 是否可修改勾選
                        }
                    }
                });
            }
        }
        $scope.handleBarcode = function(event){
            if(event && event.keyCode == 13){
                if($scope.handleData.old_seq_no != ''
                    && $scope.handleData.new_seq_no != ''){
                    $scope.addSeqno();
                }
            }
        };
        $scope.handleQrcode = function(target){
            $scope.$root.OpenScanner({
                after : function(result){
                    target = result.text;
                    if($scope.handleData.old_seq_no != ''
                        && $scope.handleData.new_seq_no != ''){
                        $scope.addSeqno();
                    }
                },
                exception: function(){
                    //目前裝置無法使用相機
                    $scope.$root.showAlert($filter('translate')('B0214.showAlert.column3'));
                },
                orientation : 'landscape'
            });
        };
        $scope.addSeqno = function(){
            var _result = ValidateOldSeq($scope.handleData.old_seq_no);
            if(_result.msg == ''){
                _new_result = ValidateNewSeq($scope.handleData.new_seq_no);
                if(_new_result.msg == ''){
                    $scope.handleData.seq_list.push({
                        master_sid : _result.master_sid,
                        sid : _result.sid,
                        old_seq_no : _result.seq_no,
                        new_seq_no : _new_result.seq_no
                    });
                    $scope.handleData.old_seq_no = '';
                    $scope.handleData.new_seq_no = '';
                } else {
                    $scope.$root.showAlert(_new_result.msg);
                }
            } else {
                $scope.$root.showAlert(_result.msg);
            }
        }
        $scope.RemoveSeqno = function(item){
            $scope.handleData.seq_list.splice($scope.handleData.seq_list.indexOf(item), 1);
        }
        // 處置紀錄
        $scope.handleLog = function(){
            $mdDialog.serviceDialog('handleLogService',{
                itemList:$scope.handleReasonList,
                callback:function(dialog){
                    $scope.handleReasonList = dialog.itemList;
                    dialog.hide();
                }
            });
        }
        // 處置
        $scope.confirm = function(){
            var _msg = '',
                _select_temp = [];

            // step 1. 2跟3要檢查勾選大於一個，1要檢查是否有選擇
            if($scope.handle_type == '1'){
                if(!$scope.now_item){
                    //請選擇一筆成品序號
                    _msg = $filter('translate')('E07.msg.pcs_no_nonselect');
                } else {
                    _select_temp.push($scope.now_item);
                }
                // step 2. 2要檢查置換的序號數量
                if($scope.handleData.seq_list.length == 0){
                    //請輸入要置換的序號
                    _msg = $filter('translate')('E07.msg.replace_seq_empty');
                }
            } else {
                _select_temp = $filter('filter')($scope.itemList, {slected:true});
                if(_select_temp.length == 0){
                    //請選擇一筆成品序號
                    _msg = $filter('translate')('E07.msg.pcs_no_nonselect');
                }
                // step 2 3要檢查原因是否輸入
                if($scope.handle_type == '3'){
                    if(_select_temp.length > 0){
                        for(var i = 0; i < _select_temp.length; i++){
                            if(!_select_temp[i].scrapped_reason_no){
                                //請輸入報廢原因
                                _msg = $filter('translate')('E07.msg.scrapped_reason_empty');
                            };
                        }
                    }
                }

                // step 4(單筆維修)只送出有勾選的工序
                if($scope.handle_type == '4'){
                    var selectProcessList = []; // 有勾選的工序list
                    if(_select_temp && _select_temp.length > 0){
                        if(_select_temp[0].detail_list == undefined)
                        {
                            _select_temp[0].detail_list = [];
                        }
                        _select_temp[0].detail_list.forEach(function(item){
                            if(item.isSelect){
                                selectProcessList.push(item);
                            }
                        });
                    }
                    _select_temp[0].detail_list = selectProcessList; // 替換成有勾選的工序list
                }
            }

            if(_msg == ''){
                pcs_error_set_process({
                    handle_type:$scope.handle_type,
                    auto_next:$scope.auto_next,
                    handle_list:_select_temp,
                    handle_reason_list:$scope.handleReasonList,
                    replace_seq_list:$scope.handleData.seq_list
                }, function(){
                    $scope.$root.showToast($filter('translate')('E07.msg.success'));
                    $scope.search();
                });
            } else {
                $scope.$root.showAlert(_msg);
            }
        };

        // 部件序號查詢
        function pcs_unit_info_get(item, callback){
            $MMWService.pageNumberInfoGet({
                    page_mode: 'pcs_unit_info_get',
                    query_condition_info:[
                        {column_name:'Master_SID', query_mode:'0', value: item.master_sid, merge_condition_model:'AND' }
                    ]
                },function(data){
                    if(typeof callback === 'function')
                        callback(data);
                }
            );
        }

        // 解綁工序全選
        $scope.selectAllSubOpSeq = function() {
            $scope.isSelectAll = !$scope.isSelectAll;

            $scope.now_item.detail_list.forEach(function(item){
                if(!$scope.isSelectAll){
                    item.isSelect = false;
                } else {
                    item.isSelect = true;
                }
            });
                
            // 系統參數 - 工位機送修強制解綁當站(PCSMaterialRepaireClear) 啟用時，第一筆工序一律勾選
            if(config.cache.sys_parameter.PCSMaterialRepaireClear == 1){
                $scope.now_item.detail_list[0].isSelect = true; // 是否勾選
                $scope.now_item.detail_list[0].isModify = false; // 是否可修改勾選
            }
        }

        // 勾選要解綁的工序
        $scope.selectSubOpSeq = function(item) {
            if(!item.isModify){
                // 此工序為必選項，不能取消
                return $scope.$root.showAlert($filter('translate')('E07.msg.column1'));
            } else {
                if(item.isSelect){
                    var isSelect = true,
                        detail_list = $scope.now_item.detail_list;
                    for(var i = 0; i < detail_list.length; i++){
                        // 如果前一道工序勾選中，就不能取消勾選
                        if(item.sub_op_seq > detail_list[i].sub_op_seq && detail_list[i].isSelect){
                            isSelect = false;
                            break;
                        }
                    }
                    if(isSelect){
                        item.isSelect = false;
                    } else {
                        // 前一道工序勾選中，不能取消勾選
                        $scope.$root.showAlert($filter('translate')('E07.msg.column2'));
                    }
                } else {
                    item.isSelect = true;
                    $scope.now_item.detail_list.forEach(function(detail){
                        // 所有大於勾選的那筆工序的數值的工序，都需要勾選
                        // 例如：有三筆工序 3、2、1，如果勾選工序 2，則工序 3 也需要勾選
                        if(item.sub_op_seq < detail.sub_op_seq){
                            detail.isSelect = true;
                        }
                    });
                }
            }
        }

        // 取得解綁工序
        function position_unbind_info_get(item, callback) {
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SN.position_unbind_info_get',
                content: {
                    lot_no: item.plot_no,
                    pdline_no: item.pdline_no,
                    op_no: item.op_no,
                    position_no: item.position_no,
                    sub_op_seq: item.sub_opsequence,
                    pcs_no: item.pcs_no
                },
                success: function (data) {
                    if(typeof(callback) == 'function'){
                        if(data.detail_list && data.detail_list.length > 0){
                            data.detail_list.forEach(function(item){
                                item.isSelect = false;
                                item.isModify = true;
                            });
                            callback(data);
                        } 
                    }
                }
            });
        }

        function ValidateOldSeq(old_seq){
            var _result = { msg:'', master_sid:'', sid:'', seq_no:old_seq};
            //檢查舊的是否在now_item內
            if(old_seq == ''){
                //請輸入序號
                _result.msg = $filter('translate')('E07.msg.seq_empty');
            } else {
                if($scope.now_item != undefined){
                    if($scope.now_item.pcs_no != old_seq){
                        var _temp = $filter('filter')($scope.subItemList, {unit_no:old_seq}, true);
                        if(_temp && _temp.length > 0){
                            //找到
                            //檢查重複
                            var _d_temp = $filter('filter')($scope.handleData.seq_list, {old_seq_no:old_seq}, true);
                            if(_d_temp && _d_temp.length > 0){
                                //輸入序號old_seq，已存在於要置換的序號列表內
                                _result.msg = $filter('translate')('E07.msg.seq_duplicate', {seq_no:old_seq});
                            } else {
                                _result.master_sid = _temp[0].master_sid;
                                _result.sid = _temp[0].sid;
                            }
                        } else {
                            //輸入序號old_seq，不存在此次要置換的成品序號與部件序號中
                            _result.msg = $filter('translate')('E07.msg.seq_notfind', {seq:old_seq});
                        }
                    } else {
                        //找到
                        //檢查重複
                        var _temp = $filter('filter')($scope.handleData.seq_list, {old_seq_no:old_seq}, true);
                        if(_temp && _temp.length > 0){
                            //輸入序號old_seq，已存在於要置換的序號列表內
                            _result.msg = $filter('translate')('E07.msg.seq_duplicate', {seq_no:old_seq});
                        } else {
                            _result.master_sid = $scope.now_item.master_sid;
                        }
                    }
                } else {
                    $scope.$root.showAlert($filter('translate')('E07.msg.pcs_no_nonselect'));
                }
            }
            return _result;
        }

        function ValidateNewSeq(new_seq){
            var _result = {msg:'', seq_no:new_seq};
            if(new_seq == ''){
                //請輸入序號
                _result.msg = $filter('translate')('E07.msg.seq_empty');
            } else {
                //檢查重複
                var _temp = $filter('filter')($scope.handleData.seq_list, {new_seq_no:new_seq}, true);
                if(_temp && _temp.length > 0){
                    //輸入序號new_seq，已存在於要置換的序號列表內
                    _result.msg = $filter('translate')('E07.msg.seq_duplicate', {seq_no:new_seq});
                }
            }
            return _result;
        };

        function pcs_error_set_process(data, callback){
            $MMWService.sendToServer({
                uri: 'ServicesSTD.Module_SN.pcs_error_set_process',
                content: data,
                success: function (data) {
                    if(typeof(callback) == 'function')
                        callback();
                }
            });
        };
    }];
});
